var express = require('express');
var router = express.Router();
var tool=require('../tools/tool');
var BaseRequest=require('../mongodb/baserequest.js');
var Model=new BaseRequest('user');

router.post('/login',async function(req,res){
    console.log(req.body)
    res.header("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
    res.header("Access-Control-Allow-Credentials","true")
    var data={message:'用户名密码错误',errorCode:10}
    var result=await Model.find({name:req.body.username,pwd:req.body.password});
    //console.log(result);
    if(result.errorCode==0){
        var doc=result.data;
        if(doc.length>0){
            if(doc[0].state=="1"){
                data.errorCode=0;
                data.message='';
                
                data.data=JSON.parse(JSON.stringify(doc[0]));
                delete data.data.pwd;
                delete data.data._id;
                delete data.data.__v;   
                data.data.realName=data.data.name;
                data.data.token='34214321';
                var d=new Date();
                d.setDate(d.getDate()+1);
                
                data.data.expDate=tool.format(d,'yyyy-MM-dd hh:mm:ss');
                req.session.user=data.data;
            }else{
                data.message='此用户已被禁用'
            }
            
        }
        res.send(data);
    }else{
        res.send(result)
    }
})
router.post('/signout',function(req,res,next){
    if(req.session && req.session.user){
        //if(isEmptyObject(req.session.user)){
            req.session.destroy();//清除session redis一起清除
            console.log('clear')
        //}
    }
    res.send({errorCode:0})
})
router.get('/user',function(req,res){
    var data={errorCode:1};
    if(req.session && req.session.user){
        data.errorCode=0;
        data.data=req.session.user;
    }
    //console.log('send',req.session);
    res.send(data);
})
router.post('/create', async function(req,res){
    var d=new Date();
    d=tool.format(d,'yyyy-MM-dd hh:mm:ss')
    var obj={
        name:req.body.name,
        pwd:req.body.pwd,
        state:req.body.state,
        time:d
    }
    var s=await Model.find({name:obj.name});
    if(s.errorCode==0 && s.data.length>0){
        res.send({errorCode:10,message:'此用户名不可用'})
    }else{
        var result=await Model.save(obj);
        res.send(result);
    }
    
})
router.post('/update',async function(req,res){
    var obj={
        name:req.body.name,
        state:req.body.state
    }
    var result=await Model.update({_id:req.body._id},obj);
    res.send(result);
})
router.post('/list',async function(req,res){
    var result=await Model.queryPage({},{page:req.body.currentPage,limit:req.body.pageSize})
    res.send(result);
})
router.post('/remove/:id',async function(req,res){
    console.log(req.params.id);
    var result=await Model.findOneAndRemove({_id:req.params.id});
    
    res.send(result);

})
module.exports=router;